<template>
  <div class="page">
    <el-table
      :data="_messageList"
      style="width: 100%"
      ref="multipleTable"
      v-loading="loading"
      :row-key="getRowKeys"
      :expand-row-keys="expands"
      @row-click="handleRowClick"
      @cell-mouse-enter="handleMouseEnter"
      @cell-mouse-leave="handleMouseLeave"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
      >
      </el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form
            label-position="left"
            class="demo-table-expand"
          >
            <el-form-item label="消息标题">
              <span>{{props.row.title}}</span>
            </el-form-item>
            <el-form-item label="发送人">
              <span>{{getSender(props.row.extras)}}</span>
            </el-form-item>
            <el-form-item label="消息内容">
              <span>{{props.row.content}}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.isProcessed!==0"
              label="处理"
            >
              <template v-if="props.row.isProcessed==1">
                <template v-if="props.row.typehood === statusConst.FRIENDS_ADDING_REQUEST">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleFriendAgreeClick(props.row)"
                  >同意</el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleFriendRefuseClick(props.row)"
                  >拒绝</el-button>
                </template>
                <template v-else-if="props.row.typehood === statusConst.GROUP_ADDING_REQUEST">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleGroupAgreeClick(props.row)"
                  >同意</el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleGroupRefuseClick(props.row)"
                  >拒绝</el-button>
                </template>
                <template v-else>
                  <el-button
                    type="text"
                    size="small"
                  >处理</el-button>
                </template>
              </template>
              <template v-else>已处理</template>
            </el-form-item>
            <el-form-item
              v-else-if="props.row.typehood===statusConst.CONFERENCE_INVITATION"
              label="处理"
            >
              <el-button
                type="text"
                size="small"
                @click="handleJoinConference(props.row)"
              >加入会议</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        label="消息标题"
        prop="title"
      ></el-table-column>
      <el-table-column
        label="消息类型"
        prop="typehood"
      >
        <template slot-scope="scope">{{getType(scope.row.typehood)}}</template>
      </el-table-column>
      <el-table-column
        label="发送人"
        prop="extras"
      >
        <template slot-scope="">测试用户1</template>
      </el-table-column>
      <el-table-column
        label="时间"
        prop="modifyTime"
      ></el-table-column>
      <el-table-column
        label="状态"
        prop="isReaded"
        align="center"
      >
        <template slot-scope="scope">
          <span
            class="status"
            :class="_statusClass(scope.row.isReaded)"
            @click.stop="handleReadedClick(scope.row)"
          >{{getStatus(scope.row.isReaded)}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
      >
        <template>
          <div class="ctrl">
            查看详情
            <i class="el-icon-arrow-down"></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="80">
        <template slot-scope="scope">
          <i
            v-show="scope.row.notificationId == currentNotifyId"
            class="el-icon-delete-solid del"
            @click.stop="handleDeleteClick(scope.row)"
          ></i>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-button
        type="primary"
        size="medium"
        plain
        icon="el-icon-check"
        :loading="readLoading"
        @click="handleReadSelectionClick"
      >已读选中</el-button>
      <el-button
        type="danger"
        size="medium"
        plain
        icon="el-icon-delete"
        :loading="deleteLoading"
        @click="handleDeleteSelectionClick"
      >删除选中</el-button>
    </div>
    <pagination
      :total="_total"
      :pageSize="_pageSize"
      @page-change="handlePageChange"
    />
    <!-- <form-dialog
      title="添加好友"
      :visible.sync="agreeVisible"
    >
      <add-friend-form
        :msgKey="currentKey"
        @cancel="handleAddFriendCancel"
        @submit="handleAddFriendSubmit"
      />
    </form-dialog> -->
  </div>
</template>

<script>
// import AddFriendForm from './form/AddFriendForm'
import {
  processed,
  readed,
  deleted
} from '@/api/notify.js'
export default {
  name: 'MessageList',
  components: {
    // AddFriendForm
  },
  props: {
    messageObject: {
      type: Object
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      statusConst: {
        // 接受
        accept: 1,
        // 拒绝
        refuse: 2,
        // 未读
        UNREAD: 0,
        // 用户注册
        USER_REGISTER: 1,
        // 添加好友请求
        FRIENDS_ADDING_REQUEST: 2,
        // 申请加群请求
        GROUP_ADDING_REQUEST: 3,
        // 邀请参加会议
        CONFERENCE_INVITATION: 4,
        // 会议被取消
        CONFERENCE_CANCEL: 5,
        // 会议结束
        CONFERENCE_FINISH: 6
      },
      currentRow: null,
      currentKey: null,
      currentPage: 1,
      agreeVisible: false,
      currentNotifyId: null,
      expands: [],
      multipleSelection: [],
      deleteLoading: false,
      readLoading: false
    }
  },
  computed: {
    _messageList () {
      if (this.messageObject && this.messageObject.list) {
        return this.messageObject.list
      } else {
        return []
      }
    },
    _total () {
      if (this.messageObject && this.messageObject.total) {
        return this.messageObject.total
      } else {
        return 0
      }
    },
    _pageSize () {
      if (this.messageObject && this.messageObject.pageSize) {
        return this.messageObject.pageSize
      } else {
        return 0
      }
    }
  },
  methods: {
    /**
     * 点击行
     */
    handleRowClick (row, column, event) {
      if (this.expands.includes(row.notificationId)) {
        this.expands = this.expands.filter(val => val !== row.notificationId)
      } else {
        this.expands.push(row.notificationId)
      }
    },
    // 提交刷新事件，后端异步删除，所以一秒后再刷新
    handleEmitRefresh () {
      this.$emit('refresh')
    },
    // 鼠标移入事件
    handleMouseEnter (row) {
      this.currentNotifyId = row.notificationId
    },
    /**
     * 鼠标移出事件
     */
    handleMouseLeave () {
      this.currentNotifyId = null
    },
    // 点击删除通知
    async handleDeleteClick (row) {
      await deleted([row.notificationId])
      this.handleEmitRefresh()
    },
    // 获取状态
    getStatus (status) {
      return status === this.statusConst.UNREAD ? '未读' : '已读'
    },
    // 状态类
    _statusClass (status) {
      return status === this.statusConst.UNREAD ? 'unread' : 'readed'
    },
    // 获取通知类型
    getType (typehood) {
      if (
        typehood === this.statusConst.FRIENDS_ADDING_REQUEST ||
        typehood === this.statusConst.GROUP_ADDING_REQUEST
      ) {
        return '好友通知'
      } else if (
        typehood === this.statusConst.CONFERENCE_INVITATION ||
        typehood === this.statusConst.CONFERENCE_CANCEL ||
        typehood === this.statusConst.CONFERENCE_FINISH
      ) {
        return '会议通知'
      } else {
        return '其他通知'
      }
    },
    // 页码变化
    handlePageChange (currentPage) {
      this.currentKey = currentPage
      this.$emit('page-change', currentPage)
    },
    // 获取发送人
    getSender (extras) {
      const senderDetail = JSON.parse(extras)?.senderDetail
      return senderDetail ? senderDetail.userName : '无'
    },
    getRowKeys (row) {
      return row.notificationId
    },
    // 已读消息
    async handleReadedClick (row) {
      await readed([row.notificationId])
      this.handleEmitRefresh()
    },
    // 处理消息
    async handleProcessed (id, result) {
      await processed(id, result)
      this.handleEmitRefresh()
    },
    // 同意好友申请
    handleFriendAgreeClick (row) {
      this.currentRow = row
      const extras = JSON.parse(row.extras)
      this.currentKey = extras.key
      this.agreeVisible = true
    },
    // 拒绝好友申请点击
    handleFriendRefuseClick (row) {
      this.currentRow = row
      const extras = JSON.parse(row.extras)
      this.currentKey = extras.key
      this.handleFriendRefuse()
    },
    // 拒绝好友申请
    handleFriendRefuse () {
      this.$request.contact.refuseFriend(
        this.currentKey,
        res => {
          this.handleProcessed(
            this.currentRow.notificationId,
            this.$GlobalConst.GlobalConst.refuse
          )
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    handleAddFriendCancel () {
      this.agreeVisible = false
    },
    handleAddFriendSubmit () {
      this.agreeVisible = false
      this.handleProcessed(
        this.currentRow.notificationId,
        this.$GlobalConst.GlobalConst.accept
      )
    },
    // 同意入群申请点击
    handleGroupAgreeClick (row) {
      this.currentRow = row
      const extras = JSON.parse(row.extras)
      this.currentKey = extras.key
      this.handleGroupAgree()
    },
    // 同意入群申请
    handleGroupAgree () {
      this.$request.contact.groupPass(
        this.currentKey,
        res => {
          this.handleProcessed(
            this.currentRow.notificationId,
            this.$GlobalConst.GlobalConst.accept
          )
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 拒绝入群申请点击
    handleGroupRefuseClick (row) {
      this.currentRow = row
      const extras = JSON.parse(row.extras)
      this.currentKey = extras.key
      this.handleGroupRefuse()
    },
    // 拒绝入群申请
    handleGroupRefuse () {
      this.$request.contact.groupRefuse(
        this.currentKey,
        res => {
          this.handleProcessed(
            this.currentRow.notificationId,
            this.$GlobalConst.GlobalConst.refuse
          )
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 获取对会议的处理结果
    handleJoinConference (row) {
      const extras = JSON.parse(row.extras)
      if (extras) {
        this.$request.conference.judgePrivate(
          extras.meetingNumber,
          res => {
            const conferenceInfo = res.data.conferenceBaseVO
            if (conferenceInfo.status === 4) {
              this.$message.info('会议已取消')
            } else if (conferenceInfo.status === 5) {
              this.$message.info('会议已结束')
            } else if (conferenceInfo.status === 1) {
              this.$message.info('会议暂未开始')
            } else if (conferenceInfo.status === 2) {
              this.openMeetingRoom(conferenceInfo.cid)
            }
          },
          err => {
            this.$message.error(err.msg)
          }
        )
      }
    },
    // 打开开会房间
    openMeetingRoom (meetingId) {
      const { href } = this.$router.resolve({
        name: 'MeetingRoom',
        query: { conferenceId: meetingId }
      })
      window.open(href, '_blank')
    },
    // 选中回调
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 删除通知
    async handleDeleteNotify (notifications) {
      this.deleteLoading = true
      await deleted(notifications)
      this.deleteLoading = false
      this.handleEmitRefresh()
      this.clearSelection()
    },
    // 删除选中
    async handleDeleteSelectionClick () {
      const notifications = this.multipleSelection.map(item => item.notificationId)
      try {
        await this.$confirm(`是否删除已选中的${notifications.length}条消息`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.handleDeleteNotify(notifications)
      } catch {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    // 已读选中
    async handleReadSelectionClick () {
      const notifications = this.multipleSelection.map(item => item.notificationId)
      this.readLoading = true
      await readed(notifications)
      this.readLoading = false
      this.handleEmitRefresh()
      this.clearSelection()
    },
    // 清除选中
    clearSelection () {
      this.$refs.multipleTable.clearSelection()
    }
  }
}
</script>

<style lang="scss" scoped>
.status {
  cursor: pointer;
}
.unread {
  color: #1b8ee9;
}
.readed {
  color: #999;
}
.ctrl {
  cursor: pointer;
}
.del {
  color: $red;
  font-size: 16px;
  cursor: pointer;
}
.page {
  padding-bottom: 20px;
  .demo-table-expand ::v-deep label {
    width: 70px;
    color: #99a9bf;
    margin-right: 30px;
    text-align: justify;
    text-align-last: justify;
  }
  .demo-table-expand .el-form-item {
    margin-bottom: 0;
  }
}
</style>
